package com.wyz.web;

import com.wyz.entity.User;
import com.wyz.entity.UserInfo;
import com.wyz.service.User2Service;
import com.wyz.utils.StringToDate;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
//        service1(req,resp);
        service2(req,resp);
    }
//  注册的时候需要往数据库添加数据 通过new对象的方式赋值
//    protected void service1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String name = req.getParameter("name");
//        String pwd = req.getParameter("pwd");
//        String sex = req.getParameter("sex");
//        String tel = req.getParameter("tel");
//        String bir = req.getParameter("bir");
//        UserInfo ui = new UserInfo(name,pwd,Integer.parseInt(sex),tel,StringToDate.STD(bir));
//        User2Service us = new User2Service();
//        boolean flag = us.addB2(ui);
//        if (flag){
//            resp.sendRedirect("login.jsp");
//        }else{
//            req.getRequestDispatcher("register.html");
//        }
//    }
//  通过BeanUtils工具包来进行映射，需要实体类的数据类型和表中的属性名相对应
    protected void service2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        try {
            UserInfo ui = new UserInfo();
            BeanUtils.populate(ui,map);
            User2Service us = new User2Service();
            boolean flag = us.addB2(ui);
            if (flag){
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }else{
                req.getRequestDispatcher("register.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
